import React, { useState, useEffect } from 'react';
import { Layout, Menu, Breadcrumb, Avatar, Dropdown, message } from 'antd';
import { 
  UserOutlined, 
  BookOutlined, 
  ShoppingCartOutlined, 
  OrderedListOutlined, 
  BarChartOutlined, 
  LogoutOutlined,
  MenuFoldOutlined,
  MenuUnfoldOutlined
} from '@ant-design/icons';
import { useNavigate, Outlet, useLocation } from 'react-router-dom';
import { authApi } from '../../api';

const { Header, Content, Sider } = Layout;

const AdminLayout = () => {
  const [collapsed, setCollapsed] = useState(false);
  const [selectedKeys, setSelectedKeys] = useState(['dashboard']);
  const navigate = useNavigate();
  const location = useLocation();
  const currentUser = authApi.getCurrentUser();

  useEffect(() => {
    // 检查用户是否已登录
    if (!authApi.isAuthenticated()) {
      message.error('请先登录');
      navigate('/admin/login');
      return;
    }
    
    // 检查用户是否是管理员
    if (!authApi.isAdmin()) {
      message.error('无权限访问管理后台');
      navigate('/');
      return;
    }

    // 根据当前路径设置选中的菜单项
    const pathSegments = location.pathname.split('/');
    const currentPath = pathSegments[pathSegments.length - 1] || 'dashboard';
    setSelectedKeys([currentPath]);
  }, [location.pathname, navigate]);

  const handleMenuClick = ({ key }) => {
    navigate(`/admin/${key}`);
  };

  const handleLogout = () => {
    authApi.logout();
    message.success('已退出登录');
    navigate('/admin/login');
  };

  // 用户菜单
  const userMenu = (
    <Menu>
      <Menu.Item key="logout" icon={<LogoutOutlined />} onClick={handleLogout}>
        退出登录
      </Menu.Item>
    </Menu>
  );

  // 面包屑导航
  const getBreadcrumb = () => {
    const pathSegments = location.pathname.split('/').filter(Boolean);
    const breadcrumbItems = [
      { title: '首页', path: '/admin' }
    ];
    
    if (pathSegments.length > 1) {
      const pageName = pathSegments[pathSegments.length - 1];
      let title = '';
      
      switch (pageName) {
        case 'dashboard':
          title = '仪表盘';
          break;
        case 'users':
          title = '用户管理';
          break;
        case 'books':
          title = '书籍管理';
          break;
        case 'orders':
          title = '订单管理';
          break;
        default:
          title = pageName;
      }
      
      breadcrumbItems.push({ title, path: location.pathname });
    }
    
    return (
      <Breadcrumb style={{ margin: '16px 0' }}>
        {breadcrumbItems.map((item, index) => (
          <Breadcrumb.Item key={index}>{item.title}</Breadcrumb.Item>
        ))}
      </Breadcrumb>
    );
  };

  return (
    <Layout style={{ minHeight: '100vh' }}>
      <Sider 
        collapsible 
        collapsed={collapsed} 
        onCollapse={setCollapsed}
        trigger={null}
      >
        <div className="logo" style={{ 
          height: '32px', 
          margin: '16px', 
          background: 'rgba(255, 255, 255, 0.2)',
          color: 'white',
          display: 'flex',
          justifyContent: 'center',
          alignItems: 'center',
          fontSize: collapsed ? '14px' : '18px',
          fontWeight: 'bold'
        }}>
          {collapsed ? '图书' : '图书商城管理'}
        </div>
        <Menu
          theme="dark"
          mode="inline"
          selectedKeys={selectedKeys}
          onClick={handleMenuClick}
          items={[
            {
              key: 'dashboard',
              icon: <BarChartOutlined />,
              label: '仪表盘'
            },
            {
              key: 'users',
              icon: <UserOutlined />,
              label: '用户管理'
            },
            {
              key: 'books',
              icon: <BookOutlined />,
              label: '书籍管理'
            },
            {
              key: 'orders',
              icon: <OrderedListOutlined />,
              label: '订单管理'
            }
          ]}
        />
      </Sider>
      <Layout className="site-layout">
        <Header 
          style={{ 
            padding: 0, 
            background: '#fff',
            display: 'flex',
            justifyContent: 'space-between',
            alignItems: 'center'
          }}
        >
          <div style={{ paddingLeft: '16px' }}>
            {React.createElement(collapsed ? MenuUnfoldOutlined : MenuFoldOutlined, {
              className: 'trigger',
              onClick: () => setCollapsed(!collapsed),
              style: { fontSize: '18px' }
            })}
          </div>
          <div style={{ paddingRight: '16px' }}>
            <Dropdown overlay={userMenu} placement="bottomRight">
              <div style={{ cursor: 'pointer', display: 'flex', alignItems: 'center' }}>
                <Avatar icon={<UserOutlined />} />
                <span style={{ marginLeft: '8px' }}>{currentUser?.username || '管理员'}</span>
              </div>
            </Dropdown>
          </div>
        </Header>
        <Content style={{ margin: '0 16px' }}>
          {getBreadcrumb()}
          <div style={{ padding: 24, minHeight: 360, background: '#fff' }}>
            <Outlet />
          </div>
        </Content>
      </Layout>
    </Layout>
  );
};

export default AdminLayout; 